package org.example.sprojcet.service.impl;

import ch.qos.logback.core.util.FileUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.sprojcet.entitys.Book;
import org.example.sprojcet.entitys.User;
import org.example.sprojcet.mapper.BookMapper;
import org.example.sprojcet.mapper.UserMapper;
import org.example.sprojcet.service.BookService;
import org.example.sprojcet.utils.FilesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional//(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class BookServiceImpl implements BookService {

    @Autowired
    private FilesUtils filesUtils; // 上传工具类

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public SaResult savaBook(MultipartFile[] files, Book book) {
        ArrayList<String> filePath = new ArrayList<>();
        for (MultipartFile file : files) {
            Map<String, Object> upload = filesUtils.upload(file);
            if (upload.get("filePath") == null) {
                return SaResult.error("请传递.jpg,.jpeg,.png格式的图片");
            }
            filePath.add(upload.get("filePath").toString());
        }
        // 假设第一个文件是封面，第二个是封底
        book.setCoverImage(filePath.get(0));
        if (filePath.size() > 1) {
            book.setBackImage(filePath.get(1));
        } else {
            // 处理没有上传封底的情况，例如设置为默认值或空
            book.setBackImage("");
        }

        // 获取当前登录用户
        String loginPhone = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, loginPhone);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            return SaResult.error("未查询出当前用户");
        }
        book.setSubmitUser(user.getId());

        // 保存书籍到数据库
        return bookMapper.insert(book) > 0 ? SaResult.ok("保存成功") : SaResult.error("保存失败");
    }
    //3.在BookServiceImpl实现类中实现getImagesNames方法
    @Override
    public List<String> getImagesname() {
        List<String> list = new ArrayList<>();
        List<Book> books = bookMapper.selectList(null);
        for (Book book : books) {
            list.add(book.getBackImage().substring(book.getBackImage().lastIndexOf("/") + 1));
            list.add(book.getCoverImage().substring(book.getCoverImage().lastIndexOf("/") + 1));
        }
        return list;
    }
    
}
